package com.haier.gimspro.util.http;

import cn.hutool.json.XML;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dtyunxi.cube.utils.SignatureUtil;
import com.haier.annotation.Log;
import com.haier.config.EnvFieldConfig;
import com.haier.modules.security.service.dto.JwtUserDto;
import com.haier.utils.MD5Utils;
import com.haier.utils.SecurityUtils;
import com.haier.utils.StringUtils;
import com.haier.utils.http.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.Charsets;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.*;

@Component
@Slf4j
public class HttpClientCommon {
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    /**
     * 用户登陆获取token信息进行登陆
     */
    public static final String loginUrl = "/gmdceqApi/appLogin";

    /**
     *生成送货指示书-海外T-3
     */
    public static final String createT3BillOverSeas = "/gmdceqApi/deliverweb/orderItemT3/createT3BillSap";
    /**
     * T-3 生成LPN看单
     */
    public static final String getT1LpnBill =  "/gmdceqApi/deliverweb/lpnBill/getT1LpnBill";
    /**
     *查询工厂对应的送货地点
     */
    public static final String factorynotoaddress = "/gmdceqApi/deliverweb/factoryaddress/factorynotoaddress";
    /**
     *生成送货指示书-海外T-3
     */
    public static final String getDeliveryBillItem = "/gmdceqApi/deliverweb/deliveryBillRead/getDeliveryBillItem";
    /**
     *撤回送货信息-GMDC
     */
    public static final String revokeDeliveryBill = "/gmdceqApi/deliverweb/deliveryBillT1/revokeDeliveryBill";
    /**
     * 大宗查询收货状态
     */
    public static final  String dazongQueryReceiveData = "/importDataToDzsp/queryReceivingInfo";

    /**
     * 大宗单据撤销
     */
    public static final  String dazongDeleteData = "/importDataToDzsp/deleteData";
    /**
     *大宗生成指示书Code
     */
    public static final String dazongSentOrderCode = "/importDataToDzsp/handleData";

    /**
     *大宗生成指示书PDF 打开地址
     */
    public static final String dazongSentPdfUrl = "/hr/haierDeliveryInstruction?applyCode=";

    /**
     * 获取大宗商品送货指示书数据
     */
    public static final String dzQueryDeliveryDataUrl = "/importDataToDzsp/queryDeliveryData";


    /**
     * GMDC生成指示书PDF 打开地址
     */
    public static final String gmdcQueryDeliveryDataUrl = "/gmdceqApi/deliverweb/modelfiledown/downModelFileNew";

//    public static void main(String[] args) {
////        httpXmlPost("http://10.138.11.87:16877/corplink/httpAccess","42002005|CL10000018|1106||#<?xml version=\"1.0\" encoding = \"UTF-8\"?><resRoot><appHdr/><appBody><immediateLongFlag>2</immediateLongFlag><validDate>20210818</validDate><overseaOrderCode>21HR-WcqhrMK000293Y</overseaOrderCode><secondAdvisingBankNameEn1></secondAdvisingBankNameEn1><secondAdvisingBankAddEn1></secondAdvisingBankAddEn1><secondAdvisingBank></secondAdvisingBank><priceTerms>DAP</priceTerms><validPlace>22</validPlace><deliveryPeriod></deliveryPeriod><beneficiaryBondedAreaEnt></beneficiaryBondedAreaEnt><add5></add5><add2></add2><goodsName></goodsName><add1></add1><beneficiaryName1>Serial Micro electronics (HK) Ltd.</beneficiaryName1><weightTolerance>0</weightTolerance><add4></add4><add3></add3><deliveryPoint/><advisingBank>ICBC</advisingBank><swiftCode2></swiftCode2><custAdd1></custAdd1><creditLetterAmt>243381</creditLetterAmt><beneficiary>cf6159650c2a4cd8af7ca630762d6b80</beneficiary><allowedTransportFlag>Y</allowedTransportFlag><beneficiaryAdd1>c/o 9 Raffles Place #17-05 Republic Plaza Singapore 048619</beneficiaryAdd1><unloadingPoint/><contractAmt>245839.0000</contractAmt><creditLetterCur>USD</creditLetterCur><overShipmentAmt>243381</overShipmentAmt><custNameCn></custNameCn><longTermLimit/><latestDelivery>20210730</latestDelivery><postscript></postscript><acceptanceBankIndicate></acceptanceBankIndicate><swiftCode/><tradeDesc>6562435963|USD|245839.0000|00010#0320401493#unot#100EA#null#USD#100#20210730#</tradeDesc><issueRegDate>20210806</issueRegDate><allowedPartialShipment>Y</allowedPartialShipment><creditLetterType>4</creditLetterType><restrictedNegotiation>N</restrictedNegotiation><confirmIndicate></confirmIndicate><custNameEn1></custNameEn1><otherLimitType></otherLimitType><limitType></limitType><LcMaxAmt>243381</LcMaxAmt><applicant>77880002</applicant><applicantBondedAreaEnt></applicantBondedAreaEnt><advisingBankAdd1></advisingBankAdd1><loadingPort/><feeDetails>test322#A#3#D^test22dfasdasd42#B#7#D^test111#A#1#C^test1232#B#6#C</feeDetails><advisingBankNameEn1>ICBC</advisingBankNameEn1><payingBank></payingBank><goodsCode></goodsCode><limitProperty></limitProperty><contractCode>6562435963</contractCode></appBody></resRoot>\n");
//        httpXmlPost("http://10.138.11.87:16877/corplink/httpAccess","");
//    }
//public static void main(String[] args) {
//    JSONObject headerInfo = new JSONObject();
//
//   String result =  httpXmlPost("http://gmdceq-vue.qd-ctcc.haier.net/gmdceqApi/appLogin", "{\"userName\":\"19017191\",\"isIdm\":\"1\",\"appKey\":\"25F7664560AF2B6DD7BD8AF46C08E07C\"}", headerInfo);
//   log.info(result);
//}
//public static void main(String[] args) {
//    sendOrderAction ("http://gmdceq-vue.qd-ctcc.haier.net","/gmdceqApi/appLogin",null,"19017191","25F7664560AF2B6DD7BD8AF46C08E07C");
//}

    @Log(value = "/送货单接口" ,isRecordResult = true)
    public  String sendOrderAction(String baseUrl,String actionUrl ,String query ,String userId,String appKey){
        JwtUserDto user = (JwtUserDto) SecurityUtils.getCurrentUser();
        JSONObject appTokenRequestInfo   = new JSONObject();
//        appTokenRequestInfo.put("userName",19017191);
        appTokenRequestInfo.put("userName",userId);
        appTokenRequestInfo.put("isIdm","1");
        appTokenRequestInfo.put("appKey",appKey);

        String appInfo = sendHttpPost(baseUrl+loginUrl,appTokenRequestInfo.toJSONString() ,new JSONObject());
        JSONObject tokenInfo =  JSON.parseObject(appInfo);
        String token = "";
        if(tokenInfo.get("success")!=null&&tokenInfo.getBoolean("success")){
            token = tokenInfo.getString("result");
        }
        if(StringUtils.isEmpty(token)){
            throw new RuntimeException("token info 未能成功获取，请重试或者联系管理员处理");
        }
        JSONObject headerInfo  = new JSONObject();
        headerInfo.put("user-access-token",token);
        headerInfo.put("app-key",appKey);
        String result  = sendHttpPost(baseUrl+actionUrl,query ,headerInfo);
        return result;

    }

    /**
     * 通用BCC接口数据内容保存处理
     *
     * @param
     */
    @Log(value = "bcc数据信息获取",isRecordResult = true)
    public String getAllBccData(String interName, String jsonParamString, EnvFieldConfig envFieldConfig) throws IOException {
//        interName = "/getFeeItem";
//        jsonParamString = "{\"pageNum\":1,\"pageSize\":10\"}";
        // 系统编码
        String applicationKey = envFieldConfig.getBccAppKey();
        // 系统密钥
        String applicationSecret = envFieldConfig.getBccAppSecret();
        // 自定义服务地址
        String url =envFieldConfig.getBccBaseUrl()+interName;
        String nonce = UUID.randomUUID().toString();
        String timestamp = System.currentTimeMillis() + "";
        String signSrc = "Application-Key=" + applicationKey + "&X-Yx-Nonce=" + nonce + "&X-Yx-Timestamp=" + timestamp;
        // 生成签名
        String signature= SignatureUtil.sign(signSrc, applicationSecret);


        CloseableHttpClient httpClient =null;
        // url为自定义服务地址
        HttpPost post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        post.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
        post.setHeader("application-key", applicationKey);
        post.setHeader("x-yx-nonce", nonce);
        post.setHeader("x-yx-timestamp", timestamp);
        post.setHeader("x-yx-signature", signature);

        // 设置body体，请求参数以实际为准
//        String body = "{\"pageNum\":1,\"pageSize\":10\"}";
        StringEntity s = new StringEntity(jsonParamString, Charsets.UTF_8);
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE));
        post.setEntity(s);

        try {
            httpClient = HttpClients.createDefault();
            // 发起调用
            CloseableHttpResponse httpResponse = httpClient.execute(post);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // do something
                HttpEntity entity2 = httpResponse.getEntity();

                cn.hutool.json.JSONObject jsonObj = XML.toJSONObject(EntityUtils.toString(entity2, "utf-8"));
                log.info(jsonObj.toJSONString(1));
                return jsonObj.toJSONString(1);
            }
        } catch (IOException e) {
            // do something
        }finally {
            if(httpClient!=null){
                httpClient.close();
            }

        }
        return null;
    }

    /**
     * bcc撤回费用付款申请单
     *
     * @param
     */
    @Log(value = "bcc撤回费用付款申请单",isRecordResult = true)
    public String getrRevertAllBccData(String interName, String jsonParamString, EnvFieldConfig envFieldConfig) throws IOException {
        // 系统编码
        String applicationKey = envFieldConfig.getBccAppKey();
        // 系统密钥
        String applicationSecret = envFieldConfig.getBccAppSecret();
        // 自定义服务地址
        String url =envFieldConfig.getBccBaseUrl()+interName;
        String nonce = UUID.randomUUID().toString();
        String timestamp = System.currentTimeMillis() + "";
        String signSrc = "Application-Key=" + applicationKey + "&X-Yx-Nonce=" + nonce + "&X-Yx-Timestamp=" + timestamp;
        // 生成签名
        String signature= SignatureUtil.sign(signSrc, applicationSecret);
        String res = null;

        CloseableHttpClient httpClient =null;
        // url为自定义服务地址
        HttpPost post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
        post.setHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
        post.setHeader("application-key", applicationKey);
        post.setHeader("x-yx-nonce", nonce);
        post.setHeader("x-yx-timestamp", timestamp);
        post.setHeader("x-yx-signature", signature);

        // 设置body体，请求参数以实际为准
        StringEntity s = new StringEntity(jsonParamString, Charsets.UTF_8);
        s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE));
        post.setEntity(s);
        try {
            httpClient = HttpClients.createDefault();
            // 发起调用
            CloseableHttpResponse httpResponse = httpClient.execute(post);
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

                // do something
                HttpEntity entity2 = httpResponse.getEntity();
                res = EntityUtils.toString(entity2, "utf-8");

            }
        } catch (IOException e) {
            // do something
        }finally {
            if(httpClient!=null){
                httpClient.close();
            }

        }

        return res;
    }


    /**
     *  方法描述：http—POST方法调服务端接口
     * @param url 调用请求地址
     * @param query 请求参数xml串
     * @return
     * @throws Exception
     */
    @Log(value = "/普通http调用接口",isRecordResult = true)
    public  String sendHttpPost(String url, String query,JSONObject headerInfo) {
        log.info("query param：" + query );
        LocalDateTime recordTime = LocalDateTime.now(); //操作时间
        LocalDateTime requestTime; //请求时间
        StringBuffer sbuffer= new StringBuffer();
        HttpURLConnection conn = null;
        try {

            URL restURL = new URL(url);
            /*
             * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
             */
            conn = (HttpURLConnection) restURL.openConnection();

            //请求方式
            conn.setRequestMethod("POST");
            //设置是否从httpUrlConnection读入，默认情况下是true; httpUrlConnection.setDoInput(true);
            conn.setDoOutput(true);
            //allowUserInteraction 如果为 true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此 URL 进行检查。
            conn.setAllowUserInteraction(false);
            //设置请求格式

            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            for(String key :headerInfo.keySet()){
                if(headerInfo.get(key)!=null&&StringUtils.isNotEmpty(headerInfo.getString(key))){
                    conn.setRequestProperty(key, headerInfo.getString(key));
                }
            }
            conn.setReadTimeout(1000*60);//设置读取超时时间   60秒       
            conn.setConnectTimeout(1000*30);//设置连接超时时间   30秒          
            conn.connect();
            requestTime = LocalDateTime.now(); //请求时间
            OutputStream out = conn.getOutputStream();//向对象输出流写出数据，这些数据将存到内存缓冲区中          
            out.write(query.getBytes("UTF-8"));            //out.write(new String("测试数据").getBytes());
            // 刷新对象输出流，将任何字节都写入潜在的流中       
            out.flush();
            // 关闭流对象,此时，不能再向对象输出流写入任何数据，先前写入的数据存在于内存缓冲区中          
            out.close();
            //读取响应           
            if (conn.getResponseCode()==200){
                logger.info("调用请求成功："+conn.getResponseCode());
                // 从服务器获得一个输入流
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                String lines;
                while ((lines = reader.readLine()) != null) {
                    sbuffer.append(lines);
                }
                logger.info("调用返回信息："+sbuffer);
                reader.close();
                if(sbuffer==null){

                }
            }else{

            }
            //断开连接           
            conn.disconnect();
        } catch (SocketTimeoutException e){
            log.error("request third-party interface error ：" , e);
        } catch (IOException e) {
            log.error("request third-party interface error ：" , e);
        }finally {
            if(conn!=null){
                conn.disconnect();
            }
        }
        return  String.valueOf(sbuffer);
    }

    /**
     *  方法描述：http—POST方法调服务端接口
     * @param url 调用请求地址
     * @param query 请求参数xml串
     * @return
     * @throws Exception
     */
    @Log(value = "/普通http调用接口",isRecordResult = true)
    public  String sendHttpPostOpsi(String url, String query,JSONObject headerInfo) {
        LocalDateTime recordTime = LocalDateTime.now(); //操作时间
        LocalDateTime  requestTime; //请求时间
        StringBuffer sbuffer= new StringBuffer();
        HttpURLConnection conn = null;
        try {

            URL restURL = new URL(url);
            /*
             * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
             */
            conn = (HttpURLConnection) restURL.openConnection();

            //请求方式
            conn.setRequestMethod("POST");
            //设置是否从httpUrlConnection读入，默认情况下是true; httpUrlConnection.setDoInput(true);
            conn.setDoOutput(true);
            //allowUserInteraction 如果为 true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此 URL 进行检查。
            conn.setAllowUserInteraction(false);
            //设置请求格式

//            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            for(String key :headerInfo.keySet()){
                if(headerInfo.get(key)!=null&&StringUtils.isNotEmpty(headerInfo.getString(key))){
                    conn.setRequestProperty(key, headerInfo.getString(key));
                }
            }
            conn.setReadTimeout(1000*60);//设置读取超时时间   60秒       
            conn.setConnectTimeout(1000*30);//设置连接超时时间   30秒          
            conn.connect();
            requestTime = LocalDateTime.now(); //请求时间
            OutputStream out = conn.getOutputStream();//向对象输出流写出数据，这些数据将存到内存缓冲区中          
            out.write(query.getBytes("UTF-8"));            //out.write(new String("测试数据").getBytes());
            // 刷新对象输出流，将任何字节都写入潜在的流中       
            out.flush();
            // 关闭流对象,此时，不能再向对象输出流写入任何数据，先前写入的数据存在于内存缓冲区中          
            out.close();
            //读取响应           
            if (conn.getResponseCode()==202){
                logger.info("调用请求成功："+conn.getResponseCode());
                // 从服务器获得一个输入流
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
                String lines;
                while ((lines = reader.readLine()) != null) {
                    sbuffer.append(lines);
                }
                logger.info("调用返回信息："+sbuffer);
                reader.close();
                if(sbuffer==null){

                }
            }else{

            }
            //断开连接           
            conn.disconnect();
        } catch (SocketTimeoutException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(conn!=null){
                conn.disconnect();
            }
        }
        return  String.valueOf(sbuffer);
    }



    @Log(value = "/送货单接口" )
    public  String sendOrderActionNotLogInfo(String baseUrl, String actionUrl , String query , String userId, String appKey, HttpServletResponse response){
        JwtUserDto user = (JwtUserDto) SecurityUtils.getCurrentUser();
        JSONObject appTokenRequestInfo   = new JSONObject();
        appTokenRequestInfo.put("userName",userId);
        appTokenRequestInfo.put("isIdm","1");
        appTokenRequestInfo.put("appKey",appKey);

        String appInfo = sendHttpPost(baseUrl+loginUrl,appTokenRequestInfo.toJSONString() ,new JSONObject());
        JSONObject tokenInfo =  JSON.parseObject(appInfo);
        String token = "";
        if(tokenInfo.get("success")!=null&&tokenInfo.getBoolean("success")){
            token = tokenInfo.getString("result");
        }
        if(StringUtils.isEmpty(token)){
            throw new RuntimeException("token info 未能成功获取，请重试或者联系管理员处理");
        }
        JSONObject headerInfo  = new JSONObject();
        headerInfo.put("user-access-token",token);
        headerInfo.put("app-key",appKey);
        String result  = sendHttpPostGetToken(baseUrl+actionUrl,query ,headerInfo,response);
        return result;

    }


    @Log(value = "/获取gemsToken接口" ,isRecordResult = true)
    public  String getGemsUserToken(String baseUrl ,String userId,String appKey){
        JwtUserDto user = (JwtUserDto) SecurityUtils.getCurrentUser();
        JSONObject appTokenRequestInfo   = new JSONObject();
        appTokenRequestInfo.put("userName",userId);
        appTokenRequestInfo.put("isIdm","1");
        appTokenRequestInfo.put("appKey",appKey);

        String appInfo = sendHttpPost(baseUrl+loginUrl,appTokenRequestInfo.toJSONString() ,new JSONObject());
        JSONObject tokenInfo =  JSON.parseObject(appInfo);
        String token = "";
        if(tokenInfo.get("success")!=null&&tokenInfo.getBoolean("success")){
            token = tokenInfo.getString("result");
        }
        if(StringUtils.isEmpty(token)){
            throw new RuntimeException("token info 未能成功获取，请重试或者联系管理员处理");
        }
        return token;

    }

    /**
     *  方法描述：http—POST方法调服务端接口
     * @param url 调用请求地址
     * @param query 请求参数xml串
     * @return
     * @throws Exception
     */
    @Log(value = "/普通http调用接口",isRecordResult = true)
    public  String sendHttpPostGetToken(String url, String query, JSONObject headerInfo, HttpServletResponse response) {
        log.info("query param：" + query );
        LocalDateTime recordTime = LocalDateTime.now(); //操作时间
        LocalDateTime  requestTime; //请求时间
        StringBuffer sbuffer= new StringBuffer();
        HttpURLConnection conn = null;
        ByteArrayOutputStream baos = null;
        try {

            URL restURL = new URL(url);
            /*
             * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
             */
            conn = (HttpURLConnection) restURL.openConnection();

            //请求方式
            conn.setRequestMethod("POST");
            //设置是否从httpUrlConnection读入，默认情况下是true; httpUrlConnection.setDoInput(true);
            conn.setDoOutput(true);
            //allowUserInteraction 如果为 true，则在允许用户交互（例如弹出一个验证对话框）的上下文中对此 URL 进行检查。
            conn.setAllowUserInteraction(false);
            //设置请求格式

            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            for(String key :headerInfo.keySet()){
                if(headerInfo.get(key)!=null&&StringUtils.isNotEmpty(headerInfo.getString(key))){
                    conn.setRequestProperty(key, headerInfo.getString(key));
                }
            }
            conn.setReadTimeout(1000*60);//设置读取超时时间   60秒       
            conn.setConnectTimeout(1000*30);//设置连接超时时间   30秒          
            conn.connect();
            requestTime = LocalDateTime.now(); //请求时间
            OutputStream out = conn.getOutputStream();//向对象输出流写出数据，这些数据将存到内存缓冲区中          
            out.write(query.getBytes("UTF-8"));            //out.write(new String("测试数据").getBytes());
            // 刷新对象输出流，将任何字节都写入潜在的流中       
            out.flush();
            // 关闭流对象,此时，不能再向对象输出流写入任何数据，先前写入的数据存在于内存缓冲区中          
            out.close();
            //读取响应           
            if (conn.getResponseCode()==200){
                logger.info("调用请求成功："+conn.getResponseCode());
//                // 从服务器获得一个输入流
//                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
//                String lines;
//                while ((lines = reader.readLine()) != null) {
//                    sbuffer.append(lines);
//                }
//                logger.info("调用返回信息："+sbuffer);
//                reader.close();


                byte[] buffer = new byte[1024];
                int len;
                baos = new ByteArrayOutputStream();
                while ((len = conn.getInputStream().read(buffer)) != -1) {
                    baos.write(buffer, 0, len);
                }
                out = response.getOutputStream();
                out.write(baos.toByteArray());


                if(sbuffer==null){

                }
            }else{

            }
            //断开连接           
            conn.disconnect();
        } catch (SocketTimeoutException e){
            log.error("request third-party interface error ：" , e);
        } catch (IOException e) {
            log.error("request third-party interface error ：" , e);
        }finally {
            if(conn!=null){
                conn.disconnect();
            }
        }
        return  String.valueOf(sbuffer);
    }


    /**
     *  方法描述：http—GET方法调服务端接口
     * @param url 调用请求地址
     * @param params 请求参数
     * @param headParams 请求头
     * @return
     * @throws Exception
     */
    @Log(value = "/普通httpGet请求调用接口",isRecordResult = true)
    public static String doHttpGet(String url, Map<String,String> params,Map<String,String> headParams) {
        String result = null;
        //1.获取httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //接口返回结果
        CloseableHttpResponse response = null;
        String paramStr = null;
        try {
            List<BasicNameValuePair> paramsList = new ArrayList<BasicNameValuePair>();

            for (String key : params.keySet()) {
                paramsList.add(new BasicNameValuePair(key,params.get(key)));
            }
            paramStr = EntityUtils.toString(new UrlEncodedFormEntity(paramsList));
            //拼接参数
            StringBuffer sb = new StringBuffer();
            sb.append(url);
            sb.append("?");
            sb.append(paramStr);

            //2.创建get请求
            HttpGet httpGet = new HttpGet(sb.toString());
            //3.设置请求和传输超时时间
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpGet.setConfig(requestConfig);
            /*此处可以添加一些请求头信息，例如：
            httpGet.addHeader("content-type","text/xml");*/
            for (String head : headParams.keySet()) {
                httpGet.addHeader(head,headParams.get(head));
            }
            //4.提交参数
            response = httpClient.execute(httpGet);
            //5.得到响应信息
            int statusCode = response.getStatusLine().getStatusCode();
            //6.判断响应信息是否正确
            if (HttpStatus.SC_OK != statusCode) {
                //终止并抛出异常
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            //7.转换成实体类
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity);
            }
            EntityUtils.consume(entity);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //8.关闭所有资源连接
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }


    /**
     *  方法描述：http—PUT方法调服务端接口
     * @param url 调用请求地址
     * @param params 请求参数
     * @param headParams 请求头
     * @return
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String doHttpPut(String url, Map<String,String> params, Map<String,String> headParams ) {

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build();
        httpPut.setConfig(requestConfig);
        for (String head : headParams.keySet()) {
            httpPut.setHeader(head,headParams.get(head));
        }

        CloseableHttpResponse httpResponse = null;
        try {

            httpPut.setEntity(new StringEntity(params.toString(), Charsets.UTF_8));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            String result = EntityUtils.toString(entity);
            return result;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (httpResponse != null) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }



    /**
     *  方法描述：http—POST方法调服务端接口
     * @param url 调用请求地址
     *               map.put("appKey", "2021082799569995");//业务内容
     *         map.put("returnType", "xml");数据类型
     *         map.put("pageNumber",pageNumber);页码
     *         map.put("batchId",batchId);批次号主键
     *         map.put("startDate",startDate);
     *         map.put("endDate",endDate);
     *         map.put("timestamp", timestamp);
     *         map.put("secretStr",
     *                 MD5Utils.getMD5(se+startDate+endDate+pageNumber+batchId+timestamp));
     * @return
     * @throws Exception
     */
    @Log(value = "/印度视图获取接口",isRecordResult = true)
    public static String getIndiaViewInfo(String url, JSONObject params) {
//        url="http://10.250.7.26:32680/api/incrementQuery";
        RestTemplate restTemplate = new RestTemplate();
        Map<String, Object> map = new HashMap<>();

        String se = params.getString("se");//密钥信息
        String startDate = params.getString("startDate");
        String endDate =  params.getString("endDate");
        int pageNumber = 1;
        String batchId = System.currentTimeMillis()+"";
        long timestamp = System.currentTimeMillis();
        map.put("appKey",  params.getString("appKey"));
        map.put("returnType", params.getString("returnType"));
        map.put("pageNumber",pageNumber);
        map.put("batchId",batchId);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("timestamp", timestamp);
        map.put("secretStr", MD5Utils.getMD5(se+startDate+endDate+pageNumber+batchId+timestamp));
        String url1 = url+"?appKey={appKey}&returnType={returnType}&pageNumber={pageNumber}&batchId={batchId}&startDate={startDate}&endDate={endDate}&timestamp={timestamp}&secretStr={secretStr}";
        String s1 = restTemplate.getForObject(url1, String.class, map);
        log.info(s1);
        JSONArray array = new JSONArray();
        JSONObject jsonInfo = JSONObject.parseObject(s1);
        if(jsonInfo!=null&&jsonInfo.getString("status")!=null&&jsonInfo.getString("status").equals("200")){
            array.addAll(jsonInfo.getJSONObject("data").getJSONArray("content"));
            Long totalCount = jsonInfo.getJSONObject("data").getLong("totalCount");
            if(totalCount>1000){
                for(int i = 2;totalCount>1000*(i-1);i++){
                    map.put("pageNumber",i);
                    String result = restTemplate.getForObject(url1, String.class, map);
                    log.info(result);
                    JSONObject jsonResult = JSONObject.parseObject(result);
                    if(jsonResult!=null&&jsonResult.getString("status")!=null&&jsonResult.getString("status").equals("200")){
                        array.addAll(jsonResult.getJSONObject("data").getJSONArray("content"));
                    }
                }

            }
        }
        log.info(JSONObject.toJSONString(array));
        return  JSONObject.toJSONString(array);
    }

    public static JSONObject postWithRest(List<NameValuePair> params, String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        try {
            try {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params);
                httpPost.setEntity(entity);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            CloseableHttpResponse response= httpClient.execute(httpPost);
            String json= EntityUtils.toString(response.getEntity());
            return JSONObject.parseObject(json);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            httpClient.close();
        }
        return null;
    }

    public static JSONObject postJson(JSONObject param, String url) {
        //定义接收数据
        JSONObject result = new JSONObject();
        HttpPost httpPost = new HttpPost(url);
        CloseableHttpClient client = HttpClients.createDefault();
        //请求参数转JOSN字符串
        StringEntity entity = new StringEntity(param.toString(), "UTF-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httpPost.setEntity(entity);
        try {
            HttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = JSON.parseObject(EntityUtils.toString(response.getEntity(), "UTF-8"));
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.put("error", "连接错误！");
        }
        //关闭连接
        try {
            client.close();
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return result;
    }

    public static void main(String[] args) {
        JSONObject params = new JSONObject();
        params.put("appKey","2022011300133555");
        params.put("se","d12af20d-adf2-417b-ba36-504a665774f2");
        params.put("startDate","2022-01-01 00:00:00");
        params.put("endDate","2022-01-15 00:00:00");
        params.put("returnType","json");
        HttpClientCommon.getIndiaViewInfo("http://10.250.7.26:32680/api/incrementQuery",params);
        params.put("appKey","2022011300133530");
        params.put("se","4264db2c-76a0-4441-a23f-f40205364f2d");
        params.put("startDate","2022-01-01 00:00:00");
        params.put("endDate","2022-01-15 00:00:00");
        params.put("returnType","json");
        HttpClientCommon.getIndiaViewInfo("http://10.250.7.26:32680/api/incrementQuery",params);
    }
}
